package com.tibco.notepad.util;

import java.util.ArrayList;
import java.util.List;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import com.alibaba.fastjson.JSON;
import com.tibco.notepad.domain.Notepad;

public final class FileUtil {
	private SharedPreferences mSharedPreferences;
	private Editor mEditor;

	@SuppressLint("CommitPrefEdits")
	public FileUtil(Context context) {
		super();
		mSharedPreferences = context.getSharedPreferences(Constant.FILE_NAME,
				Context.MODE_PRIVATE);
		mEditor = mSharedPreferences.edit();
	}

	/**
	 * 从xml 中获取list
	 * 
	 * @return
	 */
	public List<Notepad> getNotepadList() {
		List<Notepad> list = new ArrayList<Notepad>();
		String noteListStr = mSharedPreferences.getString(Constant.NOTE_LIST,
				"");
		if (!noteListStr.equals("")) {
			list = (ArrayList<Notepad>) JSON.parseArray(noteListStr,
					Notepad.class);
		}
		return list;
	}

	/**
	 * 保存list 到xml 先把list转换为json字符串
	 * 
	 * @param list
	 */
	public void saveListToXml(List<Notepad> list) {
		if ((null != list) && (list.size() > 0)) {
			mEditor.putString(Constant.NOTE_LIST, JSON.toJSONString(list));
			mEditor.commit();
		} else {
			mEditor.putString(Constant.NOTE_LIST, "");
			mEditor.commit();
		}
	}
}
